<template>
  <div>
    <el-table :data="userList">
      <el-table-column label="用户名" align="center" prop="username"></el-table-column>
      <el-table-column label="权限" align="center" prop="rank">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.rank == 1" type="success">管理员</el-tag>
          <el-tag v-if="scope.row.rank == 2">操作员</el-tag>
        </template>

      </el-table-column>
      <el-table-column label="备注信息" align="center" prop="beizhu"></el-table-column>
      <el-table-column align="center">
        <template slot="header" slot-scope="scope">
          <el-tooltip content="创建新用户" placement="top" effect="light">
            <el-button @click="openAdduser" size="mini" type="success" icon="el-icon-plus" circle></el-button>
          </el-tooltip>
        </template>
        <template slot-scope="scope">
          <el-popconfirm v-if="scope.row.username!='admin'" title="确定删除吗？" @confirm="deleteUser(scope.row)">
            <el-button type="danger" icon="el-icon-delete" slot="reference" size="mini"
                       onClick="event.cancelBubble = true"></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--      分页区域-->
    <div class="block" style="margin-top: 10px">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.page"
        :page-sizes="[10,20,50]"
        :page-size="queryInfo.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="resdata.total">
      </el-pagination>
    </div>
    <el-dialog id="addUserDialog" ref="addUserDialog" :visible.sync="addUserDialog" title="新建用户"
               :modal-append-to-body='false'
               :append-to-body="true" center @close="resetForm('newUserForm')">
      <el-form :model="newUserForm" ref="newUserForm" :rules="newUserFormRules" label-width="100px">
        <el-form-item prop="username" label="用户名：" style="margin-top: 20px" class="labelBold">
          <el-input prefix-icon="el-icon-user" placeholder="请输入用户名" v-model="newUserForm.username" clearable></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码：" class="labelBold">
          <el-input prefix-icon="el-icon-lock" placeholder="请输入密码" v-model="newUserForm.password" show-password
                    v-on:keyup.enter.native="login"></el-input>
        </el-form-item>
        <el-form-item prop="rank" label="用户权限：" style="text-align: left" class="labelBold">
          <el-radio-group v-model="newUserForm.rank" size="small">
            <el-radio label='1' border>管理员</el-radio>
            <el-radio label='2' border>操作员</el-radio>
          </el-radio-group>
          <i class="el-icon-info" style="margin:0 5px 0 10px;"></i><span>操作员无权做危险操作</span>
        </el-form-item>
        <el-form-item prop="beizhu" label="备注信息：" class="labelBold">
          <el-input v-model="newUserForm.beizhu"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="addUserDialog = false">取 消</el-button>
    <el-button type="success" @click.native="addUser">提 交</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
  import md5 from 'js-md5'
  export default {
    name: "user",
    data() {
      return {
        userList: [],
        newUserForm: {username: '', password: '', rank: '2', beizhu: ''},
        newUserFormRules: {
          username: [{required: true, message: '请输入用户名', trigger: 'blur'},],
          password: [{required: true, message: '请输入密码', trigger: 'blur'}, {
            min: 6,
            max: 15,
            message: '长度在 6 到 15 个字符',
            trigger: 'blur'
          }],
        },
        addUserDialog: false,
        queryInfo: {
          query: '',
          area: '',
          type: '',
          page: 1,
          limit: 10,
        },
        resdata: "",
      }
    },
    created() {
      this.getUsers()
    },
    methods: {
      async getUsers() {
        try {
          const {data: res} = await this.$axios.get('/api/user', {params: this.queryInfo}).catch(error => {
            this.$message.error(error)
          });
          this.userList = res.result.docs
        } catch (e) {
          console.log(e.toString())
        }

      },
      // 监听pagesize改变事件
      handleSizeChange(newSize) {
        // console.log(`每页 ${newSize} 条`)
        this.queryInfo.limit = newSize
        this.getUsers()
      },
      // // 监听页码改变
      handleCurrentChange(newPage) {
        // console.log(`当前页: ${newPage}`)
        this.queryInfo.page = newPage
        this.getUsers()
      },
      openAdduser() {
        this.addUserDialog = true
      },
      addUser(){
        this.$refs.newUserForm.validate(async valid=>{
          if(valid){
             let form = JSON.parse(JSON.stringify(this.newUserForm))
              form.password = md5(md5(form.password)+'liu008')
            const res = await this.$axios.post('/api/user',form)
            if (res.status === 200 && res.data.code === "ValidationError") {
              this.$message.error("用户名重复")
            }
            if (res.status === 200 && res.data.code === "success") {
              this.$message.success("提交成功")
              this.addUserDialog = false
              this.getUsers()
            }
          }
        })
      },
      async deleteUser(row) {
        try {
          const res = await this.$axios.delete('/api/user/' + row._id).catch(error => {
            this.$message.error(error)
          });
          if (res.status === 200 && res.data.code === "success") {
            this.$message.success("操作成功")
            this.getUsers()
          } else {
            this.$message.error("操作失败")
          }
        } catch (e) {
          console.log(e.toString())
        }

      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
    }
  }
</script>

<style lang="less" >
  #addUserDialog {
    .el-dialog__header {
      background: #409EFF;
      color: white;
    }

    .el-dialog__title {
      color: white;
      font-weight: bold;
    }

    .el-dialog__close {
      color: white;
    }

    .el-dialog__body {
      padding-top: 10px;
    }
  }

  .labelBold {
    .el-form-item__label {
      font-weight: bold;
    }
  }
</style>
